﻿#include "videoffmpeg.h"

VideoFfmpeg::VideoFfmpeg(int w, int h)
{
    width   = w;
    height  = h;

    //为每帧图像分配内存
    m_pFrameYUV = av_frame_alloc();
    // width和heigt为传入的分辨率的大小，分辨率有变化时可以以最大标准申请
    m_pFrameRGB = av_frame_alloc();
    //获取图像所需的空间
    numBytes = av_image_get_buffer_size(AV_PIX_FMT_RGB24, width, height, 1);
    //设置图像转换上下文
    m_img_convert_ctx = sws_getContext(width, height, FFMPEG_PIXEL_FORMAT, width, height, AV_PIX_FMT_RGB24, SWS_BICUBIC, NULL, NULL, NULL);

}

VideoFfmpeg::~VideoFfmpeg()
{
    av_frame_free(&m_pFrameYUV);
    av_frame_free(&m_pFrameRGB);
    av_free(m_rgbBuffer);
    sws_freeContext(m_img_convert_ctx);
}

bool VideoFfmpeg::play()
{
    if (m_rgbBuffer == nullptr) {
        return false;
    }
    avpictureFill(m_pFrameRGB, m_rgbBuffer, AV_PIX_FMT_RGB24, width, height);

    //转换图像格式，将解压出来的YUV420P的图像转换为RGB的图像
    sws_scale(m_img_convert_ctx, (uint8_t const * const *) m_pFrameYUV->data,            m_pFrameYUV->linesize, 0, height, m_pFrameRGB->data, m_pFrameRGB->linesize);

    return true;
}

